package servlet;

import entity.Data;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月09日8:52
 */

@WebServlet("/query")
public class QueryServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String spell=request.getParameter("spell");
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List<Data> datas=new ArrayList<>();
        String url="jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" select id,spell,message ")
                    .append(" from t_data ")
                    .append(" where spell like ? ")
                    .append(" or message like ? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,"%"+spell+"%");
            ps.setString(2,"%"+spell+"%");
            rs=ps.executeQuery();
            while(rs.next()){
                Data data=new Data();
                data.setId(rs.getInt("id"));
                data.setSpell(rs.getString("spell"));
                data.setMessage(rs.getString("message"));
                datas.add(data);
            }
            //将一个Java对象集合转换成JSON对象数组
            JSONArray jsonArray=JSONArray.fromObject(datas);
            PrintWriter out=response.getWriter();
            out.println(jsonArray.toString());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
